<?php
class PushController extends AppController
{
    public $name = "Push";
    public $uses = array("account");
    public $autoRender = false;

    public function get_push()
    {
        if(empty($_POST['game']) || empty($_POST['title']) || empty($_POST['msg']))
        {
            return error_common($this, __LINE__, PARAM_NULL);
        }

        $push_title = $_POST['title'];
        $push_msg = $_POST['msg'];

        if(!empty($_POST['usn']))
        {
            $push_usn = $_POST['usn'];
            $this->select_send($push_usn, $push_title, $push_msg);
        }
        else
        {
            $this->all_send($push_title, $push_msg);
        }
    }

    private function select_send($_usn, $_title, $_msg)
    {
        $push_info = $this->account->get_push_id($_usn, $this->gameName);
        $push_data = array(
            'title' => $_title,
            'msg' => $_msg,
        );

        if(empty($push_info['os']) || empty($push_info['push_id'][0]))
        {
            return error_common($this, __LINE__, OS_PUSH_ID_NULL);
        }

        if($push_info['os'] == ANDROID)
        {
            if(!gcm_push($push_data, $push_info['push_id']))
            {
                return error_common($this, __LINE__, GCM_ERROR);
            }
        }

        if($push_info['os'] == IOS)
        {
            if(!apns_push($push_data, $push_info['push_id']))
            {
                return error_common($this, __LINE__, APNS_ERROR);
            }
        }

        return success_common(0);
    }

    private function all_send($_title, $_msg)
    {
        App::import('Console/Command', 'AppShell');
        App::import('Console/Command', 'PushShell');

        $push_data = array(
            'game_name' => $this->gameName,
            'title' => $_title,
            'msg' => $_msg,
        );

        $push_info = new PushShell();
        $push_info->args = $push_data;

        $push_info->dispatchMethod('push_set');
    }
}
